#include "application.h"
#include "services/yingceservice.h"
#include "storage/localstorage.h"
#include "usersettings.h"
#include "utils/synchtask.h"
#include "yingce.h"
#include <QFile>
#include <QImage>
#include <QPixmap>
#include <QTimer>
#include <QTranslator>
#include <QWebEngineSettings>

Application::Application(int& argc, char** argv) : QApplication(argc, argv) { }

Application::~Application() { }

int Application::exec()
{
    setup();
    int ret = QApplication::exec();
    // save to file
    UserSettings::instance().save();
    delete YingCe::instance();
    delete YingCeService::instance();
    LocalStorage::instance().close();
    return ret;
}

void Application::setup()
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
#ifdef Q_OS_WIN
    // 6.7.x默认风格跟随当前系统，Windows11系统为windows11
    QApplication::setStyle(QLatin1String("windowsvista"));
#endif
#endif

    new YingCeService(this);

    // 样式
    QString style_sheet;
    QFile f(":/style/stylesheet.css");
    if (f.open(QFile::ReadOnly)) {
        style_sheet = QString::fromUtf8(f.readAll());
        f.close();
    }
#ifdef Q_OS_MAC
    QFile f2(":/style/stylesheet_mac.css");
    if (f2.open(QFile::ReadOnly)) {
        style_sheet += QString::fromUtf8(f2.readAll());
        f2.close();
    }
#endif
    setStyleSheet(style_sheet);

    QDir res_dir(applicationDirPath());
#ifdef Q_OS_MAC
    res_dir.cdUp();
#endif
    res_dir.cd("Resources");

    // 安装语言
    const QLocale locale(UserSettings::instance().language().language,
                         UserSettings::instance().language().script, QLocale::AnyCountry);
    const QList<QString> file_names = { "yingce", "qtbase" };
    const QString trans_dir { res_dir.absolutePath() };
    for (const auto& s : file_names) {
        QTranslator* t = new QTranslator(this);
        // Loads filename + prefix + ui language name + suffix(.qm)
        if (t->load(locale, s, QString('_'), trans_dir)) {
            installTranslator(t);
        } else {
            delete t;
            qDebug() << "failed to install language:" << s;
        }
    }

    // 初始化本地存储
    LocalStorage::instance().init(UserSettings::instance().rootDir().absoluteFilePath("yingce.db"));

    YingCe* yingce = new YingCe(this);
    yingce->showMainWindow();

    // 优先执行同步任务
    SynchTask* st = new SynchTask(yingce);
    yingce->mainTaskQueue()->addTask(st, false);
    yingce->mainTaskQueue()->start();

    // 检查新版本
#ifndef QT_DEBUG
    QTimer::singleShot(10000, yingce, &YingCe::autoCheckUpgrade);
#endif
}
